package containers;

import components.JStyleButton;
import dataClass.Record;
import supporter.ResourceReader;

import javax.swing.*;
import java.awt.*;
import java.time.Instant;
import java.util.Date;

public class RankPanel extends JPanel {
    private ResourceReader resourceReader = new ResourceReader();
    private long time;
    private JButton backBtn;

    public RankPanel() {
        time = System.currentTimeMillis();
        resourceReader.readRecord();
        initialise();
    }

    private void initialise() {
        if (System.currentTimeMillis() - time > 60000) {
            resourceReader.sortRecord();
            time = System.currentTimeMillis();
        }
        if (resourceReader.getRecords() == null) {
            resourceReader.sortRecord();
        }

        BorderLayout borderLayout = new BorderLayout();
        this.setLayout(borderLayout);

        JPanel center = new JPanel();
        JPanel south = new JPanel();
        FlowLayout flow = new FlowLayout(FlowLayout.LEFT,20,10);
        center.setLayout(flow);
        this.add(BorderLayout.CENTER, center);
        this.add(BorderLayout.SOUTH, south);

        String[] attrNames =
                {
                        "Rank: ",
                        "Status: ",
                        "Date: ",
                        "Time: ",
                        "Rows: ",
                };

        for (int i = 0; i < resourceReader.getRecords().size(); i++) {
            JPanel panel = new JPanel();
            FlowLayout layout = new FlowLayout(FlowLayout.LEFT,20,20);
            panel.setLayout(layout);

            Record tmp = resourceReader.getRecords().get(i);
            String[] attrs = {
                    "" + (i+1),
                    "" + tmp.getState(),
                    "" + Date.from(Instant.ofEpochMilli(tmp.getBegin())).toInstant(),
                    "" + Date.from(Instant.ofEpochMilli(tmp.getDuration())).getTime() + "s",
                    "" + tmp.getRows()
            };
            for (int j = 0; j < 5; j++) {
                JLabel label = new JLabel(attrs[j]);
                panel.add(label);
            }
            center.add(panel);
        }

        backBtn = new JStyleButton("Back");
        south.add(backBtn);
    }

    public ResourceReader getResourceReader() {
        return resourceReader;
    }

    public void setResourceReader(ResourceReader resourceReader) {
        this.resourceReader = resourceReader;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public JButton getBackBtn() {
        return backBtn;
    }

    public void setBackBtn(JButton backBtn) {
        this.backBtn = backBtn;
    }
}
